package model

import (
	"context"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"goods_srv/global"
)

var err error

type EsGoods struct {
	ID         int32 `json:"id"`
	CategoryID int32 `json:"category_id"`
	BrandsID   int32 `json:"brands_id"`
	OnSale     bool  `json:"on_sale"`
	ShipFree   bool  `json:"ship_free"`
	IsNew      bool  `json:"is_new"`
	IsHot      bool  `json:"is_hot"`

	Name        string  `json:"name"`
	ClickNum    int32   `json:"click_num"`
	SoldNum     int32   `json:"sold_num"`
	FavNum      int32   `json:"fav_num"`
	MarketPrice float32 `json:"market_price"`
	GoodsBrief  string  `json:"goods_brief"`
	ShopPrice   float32 `json:"shop_price"`
}

func (EsGoods) GetIndexName() string {
	return "goods"
}

func (EsGoods) GetMapping() string {
	goodsMapping := `{
	  "settings": {
		"number_of_shards": 1,
		"number_of_replicas": 0,
		"analysis": {
		  "analyzer": {
			"ik_smart_analyzer":{
			  "type":"custom",
			  "tokenizer":"ik_max_word"
			},
			"ik_max_word_analyzer":{
			  "type":"custom",
			  "tokenizer":"ik_max_word"
			}
		  }
		}
	  },
	  "mappings": {
		"properties": {
		  "id":{
			"type":"keyword"
		  },
		  "name":{
			"type": "text",
			"analyzer": "ik_max_word",
			"search_analyzer": "ik_max_word"
		  },
			"goods_brief": {
			"type": "text",
			"analyzer": "ik_max_word",
			"search_analyzer": "ik_max_word"
		  },
			"brands_id": {
			"type" : "integer"
		  },
			"category_id": {
			"type" : "integer"
		  },
			"on_sale": {
			"type" : "boolean"
		  },
			"ship_free": {
			"type" : "boolean"
		  },
			"is_new": {
			"type" : "boolean"
		  },
			"is_hot": {
			"type" : "boolean"
		  },
			"click_num": {
			"type" : "integer"
		  },
			"sold_num": {
			"type" : "integer"
		  },
			"fav_num": {
			"type" : "integer"
		  },
			"market_price": {
			"type" : "float"
		  },
			"shop_price": {
			"type" : "float"
		  }
		}
	  }
	}`
	return goodsMapping
}

func (EsGoods) MysqlToEs() {
	var goods []*Goods
	tx := global.DB.Model(&Goods{}).Find(&goods)
	if tx.Error != nil {
		zap.S().Panic(err)
	}
	bulkRequest := global.EsClient.Bulk()
	for _, v := range goods {
		//创建一个bulk请求动作
		req := elastic.NewBulkIndexRequest().Index(EsGoods{}.GetIndexName()).Id(string(v.ID)).Doc(v)
		bulkRequest = bulkRequest.Add(req)
	}
	_, err = bulkRequest.Do(context.Background())
	if err != nil {
		zap.S().Panic(err)
	}
	zap.S().Info("同步成功")
}
